<template>
    <a-spin tip="登录中..." :spinning="state.spinning">
        <!--    <div-->
        <!--      class="container"-->
        <!--      :style="{-->
        <!--        backgroundImage:url(state.backgroundImgUrl),-->
        <!--      }"-->
        <!--    >-->
        <div class="container">
            <div class="register-container">
                <div class="register-title"></div>
                <a-form
                        :model="state.formState"
                        :label-col="state.layoutConfig.labelCol"
                        :wrapper-col="state.layoutConfig.wrapperCol"
                        :rules="state.formRule"
                        ref="formRef"
                        layout="vertical"
                        autocomplete="off"
                >
                    <a-row>
                        <a-col :span="16">
                            <a-form-item label="邮箱" name="username">
                                <a-input
                                        v-model:value="state.formState.username"
                                        allowClear
                                        placeholder="请输入邮箱"
                                />
                            </a-form-item>

                        </a-col>
                        <a-col :span="8">
                            <a-form-item style="margin-top:31.53px;text-align: right">
                                <a-button @click="sendEmail" type="primary" :loading="state.loadingEmailCode" :disabled="state.isErrorEmail">
                                    {{state.awaitTime>0?`${state.awaitTime}s`:'发送验证码'}}
                                </a-button>
                            </a-form-item>
                        </a-col>

                    </a-row>

                    <a-form-item label="验证码" name="code">
                        <a-input
                                :disabled="state.isErrorEmail"
                                v-model:value="state.formState.code"
                                allowClear
                                placeholder="请输入验证码"
                        />
                    </a-form-item>

                    <a-form-item label="密码" name="password">
                        <a-input-password
                                :disabled="state.isErrorEmail"
                                v-model:value="state.formState.password"
                                allowClear
                                placeholder="请输入验证码"
                        />
                    </a-form-item>

                    <a-form-item label="确认密码" name="passwordBack">
                        <a-input-password
                                :disabled="state.isErrorEmail"
                                v-model:value="state.formState.passwordBack"
                                allowClear
                                placeholder="请确认密码"
                        />
                    </a-form-item>
                    <a-form-item :wrapper-col="state.submitWrapperCol" class="submit-box">
                        <a-button
                                type="primary"
                                html-type="submit"
                                @click="registerAction"
                                :loading="state.spinning"
                                style="width: 100%; font-weight: bolder"
                        >注册</a-button
                        >
                    </a-form-item>


                </a-form>
                <div class="description">
                    <span class="description-prefix">有账号？</span>
                    <span @click="jumpLogin" class="description-after">去登录</span>
                </div>
            </div>
        </div>
    </a-spin>
</template>
<script lang="ts" setup>
    import { reactive, ref } from "vue";
    import { useRouter } from "vue-router";
    import { message } from "ant-design-vue";
    import { registerUser,getEmailCode } from "@/service/user/index";
    import {aes} from '@/utils/index'
    import type { Rule } from "ant-design-vue/es/form";
    import type { FormInstance } from "ant-design-vue";
    import { useStore } from "vuex";

    interface FormStateType {
        username: string;
        password: string;
        passwordBack: string;
        code:string;
        remember: boolean;
    }
    interface FormRuleType {
        username: Object;
        password: Object;
    }
    interface stateType {
        formState: FormStateType;
        formRule: FormRuleType;
        layoutConfig: any;
        wrapperCol: any;
        submitWrapperCol: any;
        spinning: boolean;
        backgroundImgUrl: string;
        isErrorEmail:boolean,
        remoteEmailCode:string,
        loadingEmailCode:boolean,
        awaitTime:number
    }
    // 路由
    const router = useRouter();
    //store
    const store = useStore();
    const formRef = ref<FormInstance>();
    const state: stateType = reactive({
        formState: {
            code:'',
            username: "",
            password: "",
            passwordBack: "",
            remember: false,
        },
        spinning: false,
        formRule: {
            username: [{ required: true, message: "" },{validator:validatorEmail}],
            code: [{ required: true, message: "请输入验证码！" }],
            password: [{ required: true, message: "请输入密码！" }],
            passwordBack: [
                { required: true },
                { validator: validatePass, trigger: "blur" },
            ],
        },
        layoutConfig: {
            labelCol: {
                span: 8,
            },
            wrapperCol: {
                span: 24,
            },
        },
        awaitTime:-1,
        remoteEmailCode:'',
        isErrorEmail:true,
        loadingEmailCode:false,
        wrapperCol: { offset: 0, span: 24 },
        submitWrapperCol: { offset: 0, span: 24 },
        backgroundImgUrl:
            "http://www.yongma16.xyz/staticFile/common/img/background.png",
    });

    // sleep
    const sleep=(delay:number)=>{
        return new Promise(resolve=>setTimeout(resolve,delay*1000))
    }
    /**
     * 前往登录！
     */
    const jumpLogin = () => {
        // 带 hash，结果是 /about#team
        router.push({ path: "/login" });
    };
    // 确认密码
    async function validatePass(_rule: Rule, value: string) {
        if (value === "") {
            return Promise.reject("请确认密码！");
        } else if (value !== state.formState.password) {
            return Promise.reject("密码不一致!");
        } else {
            return Promise.resolve();
        }
    }
    // 校验邮箱
    async function validatorEmail(_rule: Rule, value: string) {
        if (value === "") {
            state.isErrorEmail=true
            return Promise.reject("请输入邮箱！");
        } else {
            const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if (!reg.test(value)) {
                state.isErrorEmail=true
                return Promise.reject("邮箱格式不正确!");
            }
            state.isErrorEmail=false
            return Promise.resolve();
        }
    }
    // 校验邮箱
    async function validatorEmailCode(_rule: Rule, value: string) {
        if (value!==state.remoteEmailCode) {
            return Promise.reject("验证码不正确!");
        }
        return Promise.resolve();
    }

    /**
     * 前往home！
     */
    const jumpHome = () => {
        // 带 hash，结果是 /about#team
        router.push({ path: "/" });
    };
    /**
     * 注册
     */
    const registerAction = () => {
        if (formRef.value) {
            formRef.value.validate().then((res: any) => {
                state.spinning = true;
                const params = {
                    username: state.formState.username,
                    password: aes.encrypt(state.formState.password),
                    emailCode:state.formState.code
                };
                registerUser(params)
                    .then((res: any) => {
                        state.spinning = false;
                        const { data: response } = res;
                        console.log('response',response)
                        if (response.code === 200) {
                            store.commit("user/setUserToken", response.data);
                            // 跳转
                            setTimeout(()=>{
                                jumpHome();
                            },500)
                            message.success(response.message);
                        } else {
                            message.warning(response.msg);
                        }
                    })
                    .catch((r: any) => {
                        state.spinning = false;
                        message.error(JSON.stringify(r));
                        throw Error(r);
                    });
            });
        }
    };

    const delayTime=async ()=>{
        if (state.awaitTime>0) {
            await sleep(1)
            state.awaitTime-=1
            delayTime()
        }
    };

    const sendEmail=async ()=>{
        if(state.awaitTime>0){
            return
        }
        if(!state.formState.username){
            return message.warn('请输入邮箱!')
        }
        // if(state.isErrorEmail)
        // {
        //     return message.warn('请检查邮箱格式!')
        // }
        try{
            state.loadingEmailCode=true
            const res=await getEmailCode({
                email:state.formState.username
            })
            if(res?.data?.data?.emailRes?.code==200){
                // state.remoteEmailCode=res.data.data.code
                state.isErrorEmail=false
                //  倒计时
                state.awaitTime=10
                message.success('发送邮件成功！请查收\t'+state.formState.username)
                delayTime()
            }
            else if(res?.data?.code==-1){
                state.isErrorEmail=false
                message.warn(res.data.msg)
            }
            else{
                state.isErrorEmail=false
                message.warn(res.data.data.emailRes.msg.response)
            }
        }
        catch (e) {
            message.error(JSON.stringify(e))
        }
        finally {
            state.loadingEmailCode=false
        }
    }
</script>

<style lang="less">
    .background {
        /*background: #1890ff;  !* fallback for old browsers *!*/
        /*background: -webkit-linear-gradient(to top, #000C40, #F0F2F0);  !* Chrome 10-25, Safari 5.1-6 *!*/
        /*background: linear-gradient(to top, #000C40, #F0F2F0); !* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ *!*/
    }
    .container {
        /*background: #262626;*/
        background-clip: border-box;
        position: absolute;
        width: 100vw;
        height: 100vh;
        .background();
    }
    .register-container {
        position: absolute;
        min-width: 400px;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        box-sizing: border-box;
    }
    .submit-box {
        text-align: center;
        width: 100%;
        margin: 0 auto;
    }
    .register-container {
        background-color: rgba(255, 255, 255, 0.8);
        border-radius: 10px;
        padding: 0 20px;
    }
    .register-title {
        /*background: #1890ff;*/
        /*color:#fff;*/
        width: 100%;
        text-align: center;
        font-weight: bolder;
        padding: 20px;
        font-size: 24px;
    }
    .description {
        margin-top: 20px;
        width: 100%;
        text-align: center;
        .description-after {
            color: #1890ff;
            cursor: pointer;
        }
    }
</style>
